<?php

namespace app\admin\controller\exam;

use addons\exam\enum\CommonStatus;
use app\admin\model\exam\MaterialQuestionModel;
use app\admin\model\exam\QuestionModel;
use app\common\controller\Backend;
use app\common\model\Rate;
use app\common\services\UrlService;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
use think\Cache;
use FFMpeg\FFMpeg;
use FFMpeg\FFProbe;
use FFMpeg\Format\Audio\Mp3;//你可以根据操作音频、视频类型进行引入
/**
 * 试题
 * @icon fa fa-circle-o
 */
class Question extends Backend
{

    /**
     * 
     * QuestionModel模型对象
     * @var \app\admin\model\exam\QuestionModel
     */
    protected $model = null;
    protected $noNeedRight = ['*'];
    protected $multiFields = 'status';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exam\QuestionModel;
        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("difficultyList", $this->model->getDifficultyList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("chooseList", $this->model->getChooseList());
        $this->view->assign("shortList", $this->model->getshortList());
        $this->view->assign("materialList", $this->model->getMaterialList());
        $this->view->assign("wordList", $this->model->getWordList());
        $this->view->assign("wordList", $this->model->getWordList());
        $this->view->assign("isWordList", $this->model->getIsWordList());
        $this->view->assign("hearingList", $this->model->getHearingList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['cate'])
                // ->where('is_material_child',0)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('cate')->visible(['name']);
                if(!empty($row->title)){
                    $row->title = strip_tags($row->title);
                }
            }

  
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a",'','strip_tags');
            // if ($params['options_extend']) {
            //     $params['options_extend'] = json_decode(urldecode($params['options_extend']), true);
            // }
            // dd($params);
            if ($params) {
                $params = $this->preExcludeFields($params);

                if(($params['hearing'] == 1) ){
                    if( empty($params['title_audio']) ){
                        return $this->error('听力题，必须上传题目视频');
                    }
                }

                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);

                if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
                    $params['m_type'] = 1;
                }

                if($params['kind'] == 'SHORT'){
                    $params['m_type'] = 6;
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $params['letter'] = mb_substr($params['title'],0,1);
                    $result = $this->model->allowField(true)->save($params);

                    // 保存材料题父题目
                    $this->saveMaterialParentQuestion($this->model);
                    // 保存材料题子题目
                    $this->saveMaterialQuestions($this->model, $params['material_questions'] ?? []);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids, [
            'material_questions' => function ($query) {
                return $query->with([
                    'question' => function ($query) {
                        return $query->with('cates');
                    }
                ])->order('weigh');
            }
        ]);
      
        // dd($row->toArray()['material_questions']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
          
            $params = $this->request->post("row/a",'','strip_tags');
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                if(($params['hearing'] == 1) ){
                    if( empty($params['title_audio']) ){
                        return $this->error('听力题，必须上传题目视频');
                    }
                }
                
                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);
                

                if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
                    $params['m_type'] = 1;
                }

                if($params['kind'] == 'SHORT'){
                    $params['m_type'] = 6;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    // 首字母排序
                    $params['letter'] = mb_substr($params['title'],0,1);
                   
                    $result = $row->allowField(true)->save($params);

                    // 保存材料题父题目
                    $this->saveMaterialParentQuestion($row);
                    // 保存材料题子题目
                    $this->saveMaterialQuestions($row, $params['material_questions'] ?? []);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 选项图片页面
     * @return string
     */
    public function image()
    {
        if ($this->request->isPost()) {
            $this->success($this->request->post());
        }
        return $this->view->fetch();
    }

    public function importExcel()
    {
        if ($this->request->isPost()) {
            $cate = $this->request->param('cate');
            $kind = $this->request->param('kind');
            if (!$cate) { //  || !$exam_type
                $this->error('请先选择所属题库及试题类型再进行上传');
            }
            if(!$kind){
                $this->error('请先选择所属类型及考试分类再进行上传');
            }
            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }

            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            if ($ext === 'csv') {
                $file     = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp       = fopen($filePath, "w");
                $n        = 0;
                while ($line = fgets($file)) {
                    $line     = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    throw new \Exception(__('Unknown data format'));
                }
                $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
                $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                switch ($kind) {
                    case 'JUDGE':
                        $fields = ['short_title','hearing','point','score','limit_time','translate','title_video','title_img','title_audio','title','explain','explain_translate','explain_audio','answer','A','B','difficulty','origin','example','example_translate','example_audio','status'];
                        break;
                    case 'SINGLE':
                    case 'MULTI':
                        $fields = ['short_title','hearing','point','score','limit_time','translate','title_video','title_img','title_audio','title','explain','explain_translate','explain_audio','answer','A','B','C','D','E','F','G','H','difficulty','origin','example','example_translate','example_audio','status'];
                        break;
                    case 'FILL':
                        $fields = ['short_title','hearing','point','score','limit_time','translate','title_video','title_img','title_audio','title','explain','explain_translate','explain_audio','answer','difficulty','origin','example','example_translate','example_audio','status'];
                        break;
                    case 'SHORT':
                        $fields = ['short_title','hearing','point','score','limit_time','translate','title_video','title_img','title_audio','title','explain','explain_translate','explain_audio','answer','difficulty','origin','example','example_translate','example_audio','status','xf_short_content'];
                        break;
                    case 'WORD':
                        $fields = ['short_title','hearing','point','score','limit_time','translate','title_video','title_img','title_audio','title','explain','explain_translate','explain_audio','difficulty','origin','example','example_translate','example_audio','status','is_read','is_word','xf_content','vocabulary','number_replace'];
                        break;
                    default:
                        throw new \Exception('试题类型错误');
                }
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;

                    }
                    // $temp    = array_combine($fields, $values);
                    $row     = [];
                    $options = [];

                    // 选项及字段组合
                    for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
                        $field = $fields[$i];
                        $value = $values[$i];

                        if ($i > 33) {
                            if (!empty($value) || $value == '0') {
                                $options[$field] = $value;
                            }
                        } else {
                            $row[$field] = $value;
                        }
                    }

                    // 过滤空行
                    if (!$row['title']) {
                        continue;
                    }
                    $yesorno = ['是'=>1,'否'=>0];
                    // 特殊字段处理
                    foreach ($row as $key => $item) {
                        if ($key == 'hearing') {
                            $item = $item ? $item :'否';
                            $item = $yesorno[$item];
                        }
                        if($key == 'difficulty'){
                            $diff = ['简单'=>'EASY','普通'=>'GENERAL','困难'=>'HARD'];
                            $item = $item ? $item :'简单';
                            $item = $diff[$item];
                        }
                        if($key == 'status'){
                            $diff = ['正常'=>'NORMAL','隐藏'=>'HIDDEN'];
                            $item = $item ? $item :'正常';
                            $item = $diff[$item];
                        }
                        if($key == 'is_read'){
                            $item = $item ? $item :'否';
                            $item = $yesorno[$item];
                        }
                        if($key == 'is_word'){
                            $item = $item ? $item :'是';
                            $yesornos = ['是'=>0,'否'=>1];
                            $item = $yesornos[$item];
                        }
                        $row[$key] = $item;
                    }
                    // 判断题特殊情况处理
                    if ($kind == 'JUDGE') {
                        switch ($row['answer']) {
                            case '正确':
                            case '对':
                                $row['answer'] = 'A';
                                break;
                            case '错误':
                            case '错':
                                $row['answer'] = 'B';
                                break;
                        }

                        $options = $options ? $options : ['A' => '正确', 'B' => '错误'];
                    }
                    if(!isset($row['answer'])) $row['answer'] = '';

                    // 答案特殊处理
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace('，', ',', $row['answer']);
                    if ($kind == 'MULTI' && !strpos($row['answer'], ',')) {
                        throw new \Exception('题目【' . $row['title'] . '】答案格式有误');
                    }
                    // 填空题
                    if ($kind == 'FILL') {
                        $row['answer'] = explode('|||', $row['answer']);
                        $fill_count    = count(explode('______', $row['title'])) - 1;
                        $answer_count  = count($row['answer']);

                        if ($fill_count != $answer_count) {
                            throw new \Exception('题目【' . $row['title'] . '】填空位与答案数量不匹配');
                        }

                        $fill_answers = [];
                        foreach ($row['answer'] as $item) {
                            $fill_answers[] = ['answers' => explode(',', $item)];
                        }

                        $row['answer'] = json_encode($fill_answers, JSON_UNESCAPED_UNICODE);
                    }
                    // 简答题
                    if ($kind == 'SHORT') {

                        $row['answer'] = explode('|||', $row['answer']);
                        if ($row['answer']) {
                            $short_type = substr($row['answer'][0],0,strrpos($row['answer'][0],'-')) ? substr($row['answer'][0],0,strrpos($row['answer'][0],'-')) :'文本';
                            $answer = $short_type ? substr($row['answer'][0],strrpos($row['answer'][0],'-')+1) : $row['answer'][0];
                            $short_answers = [
                                'answer' => $answer,
                                'config' => [],
                            ];

                            if (isset($row['answer'][1]) && $row['answer'][1]) {
                                $keywords = explode(',', str_replace('，', ',', $row['answer'][1]));
                                foreach ($keywords as $keyword) {
                                    $keywd = explode('-', $keyword);

                                    $short_answers['config'][] = [
                                        'answer' => $keywd[0],
                                        'score'  => $keywd[1] ?? 1,
                                    ];
                                }
                            }

                            $row['answer'] = json_encode($short_answers, JSON_UNESCAPED_UNICODE);
                        }
                    }
                    if(!isset($row['xf_short_content'])) $row['xf_short_content'] = '';
                    $row['options_json'] = json_encode($options, JSON_UNESCAPED_UNICODE);
                    $row['cate_id']      = $cate;
                    $row['kind']      = $kind;
                    // $row['exam_type_id'] = $exam_type;
                    unset($row['A'],$row['B'],$row['C'],$row['D'],$row['E'],$row['F'],$row['G'],$row['H']);
                    $insert[] = $row;
                }
                Session::set('import_question', $insert);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }
            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $this->success('识别成功', '', ['count' => count($insert)]);
        }
        $this->error('错误的提交方式');
    }
    /**
     * 试题导入
     */
    public function importExcel1()
    {
        if ($this->request->isPost()) {
            // parent::import();
            $cate = $this->request->param('cate');
            // $exam_type = $this->request->param('exam_type');
            if (!$cate) { //  || !$exam_type
                $this->error('请先选择所属类型及考试分类再进行上传');
            }

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }

            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            if ($ext === 'csv') {
                $file     = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp       = fopen($filePath, "w");
                $n        = 0;
                while ($line = fgets($file)) {
                    $line     = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    throw new \Exception(__('Unknown data format'));
                }
                $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
                $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields          = [
                    'short_title',
                    'hearing',
                    'point',
                    'score',
                    'limit_time',
                    'translate',
                    'title_video',
                    'title_img',
                    'title_audio',
                    'kind',
                    'title',
                    'explain',
                    'explain_translate',
                    'explain_audio',
                    'answer',
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                    'difficulty',
                    'origin',
                    'example',
                    'example_translate',
                    'example_audio',
                    'status',
                    'is_read',
                    'is_word',
                    'xf_content',
                    'vocabulary',
                    'number_replace',
                ];

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;

                    }
                    // $temp    = array_combine($fields, $values);
                    $row     = [];
                    $options = [];

                    // 选项及字段组合
                    for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
                        $field = $fields[$i];
                        $value = $values[$i];

                        if ($i > 33) {
                            if (!empty($value) || $value == '0') {
                                $options[$field] = $value;
                            }
                        } else {
                            $row[$field] = $value;
                        }
                    }

                    // 过滤空行
                    if (!$row['title']) {
                        continue;
                    }
                    $yesorno = ['是'=>1,'否'=>0];
                    // 特殊字段处理
                    foreach ($row as $key => $item) {
                        if ($key == 'hearing') {
                            $item = $item ? $item :'否';
                            $item = $yesorno[$item];
                        }
                        if($key == 'difficulty'){
                            $diff = ['简单'=>'EASY','普通'=>'GENERAL','困难'=>'HARD'];
                            $item = $item ? $item :'简单';
                            $item = $diff[$item];
                        }
                        if($key == 'status'){
                            $diff = ['正常'=>'NORMAL','隐藏'=>'HIDDEN'];
                            $item = $item ? $item :'正常';
                            $item = $diff[$item];
                        }
                        if($key == 'is_read'){
                            $item = $item ? $item :'否';
                            $item = $yesorno[$item];
                        }
                        if($key == 'is_word'){
                            $item = $item ? $item :'是';
                            $yesornos = ['是'=>0,'否'=>1];
                            $item = $yesornos[$item];
                        }
                        if ($key == 'kind') {
                            switch ($item) {
                                case '判断':
                                case '判断题':
                                    $item = 'JUDGE';
                                    break;
                                case '单选':
                                case '单选题':
                                    $item = 'SINGLE';
                                    break;
                                case '多选':
                                case '多选题':
                                    $item = 'MULTI';
                                    break;
                                case '填空':
                                case '填空题':
                                    $item = 'FILL';
                                    break;
                                case '问答':
                                case '问答题':
                                    $item = 'SHORT';
                                    break;
                                case '词汇':
                                case '词汇题':
                                    $item = 'WORD';
                                    break;
                            }
                        }

                        $row[$key] = $item;
                    }

                    // 判断题特殊情况处理
                    if ($row['kind'] == 'JUDGE') {
                        switch ($row['answer']) {
                            case '正确':
                            case '对':
                                $row['answer'] = 'A';
                                break;
                            case '错误':
                            case '错':
                                $row['answer'] = 'B';
                                break;
                        }

                        $options = $options ? $options : ['A' => '正确', 'B' => '错误'];
                    }

                    // 答案特殊处理
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace('，', ',', $row['answer']);
                    if ($row['kind'] == 'MULTI' && !strpos($row['answer'], ',')) {
                        throw new \Exception('题目【' . $row['title'] . '】答案格式有误');
                    }
                    // 填空题
                    if ($row['kind'] == 'FILL') {
                        $row['answer'] = explode('|||', $row['answer']);
                        $fill_count    = count(explode('______', $row['title'])) - 1;
                        $answer_count  = count($row['answer']);

                        if ($fill_count != $answer_count) {
                            throw new \Exception('题目【' . $row['title'] . '】填空位与答案数量不匹配');
                        }

                        $fill_answers = [];
                        foreach ($row['answer'] as $item) {
                            $fill_answers[] = ['answers' => explode(',', $item)];
                        }

                        $row['answer'] = json_encode($fill_answers, JSON_UNESCAPED_UNICODE);
                    }
                    // 简答题
                    if ($row['kind'] == 'SHORT') {

                        $row['answer'] = explode('|||', $row['answer']);
                        if ($row['answer']) {
                            $short_type = substr($row['answer'][0],0,strrpos($row['answer'][0],'-')) ? substr($row['answer'][0],0,strrpos($row['answer'][0],'-')) :'文本';
                            $answer = $short_type ? substr($row['answer'][0],strrpos($row['answer'][0],'-')+1) : $row['answer'][0];
                            $short_answers = [
                                'answer' => $answer,
                                'config' => [],
                            ];

                            if (isset($row['answer'][1]) && $row['answer'][1]) {
                                $keywords = explode(',', str_replace('，', ',', $row['answer'][1]));
                                foreach ($keywords as $keyword) {
                                    $keywd = explode('-', $keyword);

                                    $short_answers['config'][] = [
                                        'answer' => $keywd[0],
                                        'score'  => $keywd[1] ?? 1,
                                    ];
                                }
                            }

                            $row['answer'] = json_encode($short_answers, JSON_UNESCAPED_UNICODE);
                        }
                    }

                    $row['options_json'] = json_encode($options, JSON_UNESCAPED_UNICODE);
                    $row['cate_id']      = $cate;
                    // $row['exam_type_id'] = $exam_type;
                    unset($row['A'],$row['B'],$row['C'],$row['D'],$row['E'],$row['F'],$row['G'],$row['H']);
                    $insert[] = $row;
                }
                Session::set('import_question', $insert);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $this->success('识别成功', '', ['count' => count($insert)]);
        }
        $this->error('错误的提交方式');
    }

    /**
     * 试题导入提交
     * @return string|void
     */
    public function import()
    {
        if ($this->request->isPost()) {
            // 加载数据
            $insert = Session::pull('import_question');
            if (!$insert) {
                $this->error(__('没有可以导入的数据，请重新上传Excel文件'));
            }

            try {
                $this->model->saveAll($insert);
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                    $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                };
                $this->error($msg);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            $this->success();
        }
        $this->view->assign("kindList", [
            'JUDGE'    => '判断题',
            'SINGLE'   => '单选题',
            'MULTI'    => '多选题',
            'FILL'     => '填空题',
            'SHORT'    => '问答题',
            'WORD'     => '词汇题'
        ]);
        return $this->view->fetch();
    }

    /**
     * 获取题库数量
     */
    public function getCount()
    {
        $cate_ids = $this->request->param('cate_ids');

        if (!$cate_ids) {
            $this->error('请先选择题库');
        }

        $this->success('', '', $this->model->getCount($cate_ids));
    }

    /**
     * 选择题目页面
     */
    public function select()
    {
        $ids = input('ids');
        if(!empty($ids)){
            Cache::set('select_question',$ids,600);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['cate'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('cate')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            
            return json($result);
        }
        return $this->view->fetch();
    }

    public function test()
    {
        $this->success('', '', Session::get('import_question'));
    }

    /**
     * 检查答案输入
     * @param $params
     */
    protected function checkAnswer(&$params)
    {
        $answer  = $params['answer'] ?? '';
        $options = $params['options_json'] ?? [];

        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!$answer) {
                $this->error('请设置题目答案');
            }
            if (!$options) {
                $this->error('请设置题目选项');
            }

            $options     = json_decode($options, true);
            $option_keys = array_keys($options);

            // 多选题
            if (strpos($answer, ',') !== false) {
                $answer_arr = explode(',', trim($answer));
                foreach ($answer_arr as $item) {
                    if (!in_array($item, $option_keys)) {
                        $this->error('答案设置有误，答案选项不存在');
                    }
                }
            } else {
                if (!in_array($answer, $option_keys)) {
                    $this->error('答案设置有误，答案选项不存在');
                }
            }
        }

        // 后期拓展题型
        switch ($params['kind']) {
            // 填空题
            case 'FILL':
                if (!is_array($answer) || !count($answer)) {
                    $this->error('未设置填空题答案，至少设置一个');
                }

                // 转json
                $params['answer'] = json_encode($params['answer'], JSON_UNESCAPED_UNICODE);
                break;
                
            // 问答题
            case 'SHORT':
                $answer = $params['short_answer'] ?? '';
                if (!$answer) {
                    $this->error('请设置问答题标准答案');
                }
                $answer_config = $params['answer_config'] ?? [];
                if (!$answer_config) {
                    $this->error('请设置问答题答案关键词');
                }

                foreach ($answer_config as &$item) {
                    if (!$item['answer']) {
                        $this->error('问答题答案关键词不能为空');
                    }
                    if (!is_numeric($item['score']) || $item['score'] < 0) {
                        $this->error('问答题分数设置有误，必须为数字且不能小于0');
                    }

                    // $item['score'] = 0;
                }

                // 转json
                $params['answer'] = json_encode([
                    'answer' => $answer,
                    'config' => $answer_config
                ], JSON_UNESCAPED_UNICODE);
                break;

            // 问答题
            case 'CALL':
                
                $user_config = $params['user_config'] ?? [];
                if (!$user_config) {
                    $this->error('请设置人物');
                }


                $answer_config = $params['answer_config'] ?? [];
                if (!$answer_config) {
                    $this->error('请设置通话');
                }
                
                foreach ($user_config as &$u_config) {
                    if(isset($u_config['status']) && ($u_config['status'] == 'on')){
                        $u_config['status'] = true;
                    }else{
                        $u_config['status'] = false;
                    }
                }
                
                // 转json
                $params['answer'] = json_encode([
                    'answer' => $answer,
                    'config' => $answer_config,
                    'user'   => $user_config
                ], JSON_UNESCAPED_UNICODE);
                break;
                
            // 材料题
            case 'MATERIAL':
                // dd([$params, $answer, $options]);

                if ($params['is_material_child']) {
                    $this->error('题型设置有误，材料题不能再设置为材料题的子题');
                }

                $params['is_material_child']    = 0;
                $params['material_question_id'] = 0;
                $params['material_questions']   = $params['material_questions'] ? json_decode($params['material_questions'], true) : [];
                if (!$params['material_questions']) {
                    if ($params['status'] == CommonStatus::NORMAL) {
                        $this->error('请设置材料题的子题（或者状态先设置隐藏）');
                    }
                }

                // foreach ($params['material_questions'] as $material_question) {
                //     if ($material_question['kind'] == 'MATERIAL') {
                //         $this->error('材料题的子题不能为材料题');
                //     }
                // }

                // 转json
                $params['answer'] = json_encode([
                    'questions' => $params['material_questions']
                ], JSON_UNESCAPED_UNICODE);
                break;
        }

        if ($params['is_material_child']) {
            $params['material_question_id'] = $params['material_question_id'] ?? 0;
            if (!$params['material_question_id']) {
                $this->error('请设置材料题的父题');
            }
            if ($params['material_score'] <= 0) {
                $this->error('请设置材料题子题的分数');
            }
        }
    }

    /**
     * 保存材料题父题
     * @param $question
     * @return void
     */
    protected function saveMaterialParentQuestion($question)
    {
        if (!$question || !$question['is_material_child'] || $question['kind'] == 'MATERIAL') {
            return;
        }
        if ($parentQuestion = QuestionModel::where('id', $question['material_question_id'])
            ->where('kind', 'MATERIAL')
            ->find()) {
            $answer = json_decode($parentQuestion->answer, true);
            if (!$answer) {
                $answer = [
                    'questions' => [
                        [
                            'id'            => $question['id'],
                            'score'         => $question['material_score'],
                            'answer'        => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                            'answer_config' => null,
                        ]
                    ],
                ];
            } else {
                $has_child = false;
                foreach ($answer['questions'] as &$child_question) {
                    if ($child_question['id'] == $question['id']) {
                        $has_child                = true;
                        $child_question['score']  = $question['material_score'];
                        $child_question['answer'] = is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'];
                        break;
                    }
                }

                if (!$has_child) {
                    $answer['questions'][] = [
                        'id'            => $question['id'],
                        'score'         => $question['material_score'],
                        'answer'        => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                        'answer_config' => null,
                    ];
                }
            }

            // 材料题父题答案追加子题设置
            $parentQuestion->answer = json_encode($answer, JSON_UNESCAPED_UNICODE);
            $parentQuestion->save();

            if ($materialQuestion = MaterialQuestionModel::where('parent_question_id', $question['material_question_id'])
                ->where('question_id', $question['id'])
                ->find()) {
                $materialQuestion->score  = $question['material_score'];
                $materialQuestion->answer = is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'];
                $materialQuestion->save();
            } else {
                // 保存材料题子题关联
                MaterialQuestionModel::create([
                    'parent_question_id' => $question['material_question_id'],
                    'question_id'        => $question['id'],
                    'score'              => $question['material_score'],
                    'answer'             => $question['answer'],
                    'weigh'              => 0,
                ]);
            }

        } else {
            $this->error('未找到所属材料题');
        }
    }

    /**
     * 保存材料题子题
     * @param $parentQuestion
     * @param $questions
     * @return void
     */
    protected function saveMaterialQuestions($parentQuestion, $questions)
    {
        if (!$parentQuestion || $parentQuestion['kind'] != 'MATERIAL' || !$questions) {
            return;
        }
        // 删除旧的子题
        MaterialQuestionModel::where('parent_question_id', $parentQuestion->id)->delete();

        // 保存新的子题
        $inserts = [];
        foreach ($questions as $key => $question) {
            $inserts[] = [
                'parent_question_id' => $parentQuestion->id,
                'question_id'        => $question['id'],
                'score'              => $question['score'],
                'answer'             => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                'weigh'              => $key,
                'createtime'         => time(),
            ];
        }
        (new MaterialQuestionModel())->saveAll($inserts);
    }

    /**
     * 处理选项图片链接域名
     * @param $data
     */
    protected function optionsImage(&$data)
    {
        $options_img = $data['options_img'] ?? [];
        $options_img = json_decode($options_img, true);
        if ($options_img) {
            foreach ($options_img as &$item) {
                if (strpos($item['value'], '://') === false) {
                    $item['value'] = cdnurl($item['value'], true);
                }
            }
        }
        $data['options_img'] = json_encode($options_img);
        $data['options_img'] = $data['options_img'] == 'null' ? [] : $data['options_img'];
    }

    /**
     * 检查题目内容输入
     * @param $params
     */
    protected function checkTitle(&$params)
    {
        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!($params['title'] ?? '')) {
                $this->error('请输入题目内容');
            }
        } else if ($params['kind'] == 'FILL') {
            if (!($params['title_fill'] ?? '')) {
                $this->error('请输入填空题题目内容');
            }
            $params['title'] = $params['title_fill'];
        }
    }

    public function soundupload()
    {
        return $this->view->fetch();
    }

    public function synthesis()
    {
        $str = $this->request->post('str');
        $arr = explode(',',$str);
        foreach ($arr as $k=>$v){
            $childurl = urlService::getFileUrl($v);
            //将文件拉去下来
            $getbinary = file_get_contents($childurl,false,stream_context_create([
                "ssl" => [
                    "verify_peer"=>false,
                    "verify_peer_name"=>false,
                ]
            ]));
            $upload_dir = $_SERVER['DOCUMENT_ROOT'].'/getfile/';// 上传文件夹必须存在，否则将移动失败！
            file_put_contents($upload_dir.substr($v,strrpos($v,'/')+1),$getbinary);
            $arr[$k] = $upload_dir.substr($v,strrpos($v,'/')+1);
            sleep(1);
        }
        $url = $this->mergeAudioFiles($arr);
        return json(['status'=>1,'url'=>$url]);
    }

    function mergeAudioFiles($audio_lits)
    {
        $head = 'ffmpeg';
        $audio_lits = array_map(function($v){
            return ' -i '.$v;
        },$audio_lits);
        $flow = '';
        $listcount = count($audio_lits);
        for ($i=0;$i<$listcount;$i++){
            $flow.= '['.$i.':a]';
        }
        $outdir = '/makeaudio/output.mp3';
        $outfile = $_SERVER['DOCUMENT_ROOT'].$outdir;
        $command = $head.implode('',$audio_lits).' -filter_complex "'.$flow.'concat=n='.$listcount.':v=0:a=1[out]" -map "[out]" '.$outfile;

        shell_exec($command);
        return $_SERVER['HTTP_ORIGIN'].$outdir;
    }


}
